"""
VCProj format XML Writer
"""

from xml.dom import Node

def sortForVCPrj(array_src):
   array_out = []
   sort_array = [ 
      #VisualStudioProject
         "ProjectType",
         "Version",
      	"Name",
      	"ProjectGUID",
      	"RootNamespace",
      	"SccProjectName",
         "SccAuxPath",
      	"SccLocalPath",
      	"SccProvider",
      	"Keyword",
      #Configuration
         "OutputDirectory", 
         "IntermediateDirectory",
         "ConfigurationType",
         "InheritedPropertySheets",
         "UseOfMFC",
			"UseOfATL",
         "ATLMinimizesCRunTimeLibraryUsage",
         "CharacterSet",
         "ManagedExtensions",
		#CompilerTool
         "Optimization", 
         "InlineFunctionExpansion",
         "EnableIntrinsicFunctions",
         "FavorSizeOrSpeed",
         "OmitFramePointers",
         "WholeProgramOptimization",
         "EnableFiberSafeOptimizations",
         "LinkLibraryDependencies",
         "AdditionalOptions",
         "AdditionalIncludeDirectories",
         "PreprocessorDefinitions", 
         "IgnoreStandardIncludePath",
         "StringPooling",
         "MinimalRebuild",
         "ExceptionHandling",
         "BasicRuntimeChecks",
         "RuntimeLibrary",
         "StructMemberAlignment",
         "BufferSecurityCheck",
         "EnableFunctionLevelLinking",
         "EnableEnhancedInstructionSet",
         "FloatingPointModel",
         "DisableLanguageExtensions",
         "TreatWChar_tAsBuiltInType",
			"ForceConformanceInForLoopScope",
         "RuntimeTypeInfo",
			"OpenMP",
         "UsePrecompiledHeader",
         "PrecompiledHeaderThrough",
         "PrecompiledHeaderFile",
         "AssemblerListingLocation",
         "ObjectFile",
         "ProgramDataBaseFileName",
         "WarningLevel",
         "Detect64BitPortabilityProblems",
      #LinkerTool
         "IgnoreImportLibrary",
         "AdditionalDependencies",
         "OutputFile",
         "AdditionalLibraryDirectories",
         "SuppressStartupBanner",
         "DebugInformationFormat",
      #other
         "CallingConvention",
         "TrapIntegerDivides",
         "Prescheduling",
         "InlineAssembly",
         "CallAttributedProfiling",
         "CompileAs",
         "MkTypLibCompatible",
         "TargetEnvironment",
         "GenerateStublessProxies",
         "TypeLibraryName",
         "HeaderFileName",
         "DLLDataFileName",
         "InterfaceIdentifierFileName",
         "ProxyFileName",
         "LinkIncremental",
			"GenerateManifest",
			"IgnoreAllDefaultLibraries",
         "IgnoreDefaultLibraryNames",
         "GenerateDebugInformation",
			"AssemblyDebug",
			"ProgramDatabaseFile",
			"OptimizeReferences",
			"EnableCOMDATFolding",
			"SetChecksum",
         "SubSystem",
         "TargetMachine",
         "FixedBaseAddress",
      #DeploymentTool
			"AdditionalFiles",
			"RemoteRoot",
			"Progress",
			"DeploymentType",
 		#PostBuildEventTool
			"Description",
			"CommandLine" ]
        
        
   dbg_len_start = len(array_src)
   
   for name_sort in sort_array:
      if name_sort in array_src:
         array_src.remove(name_sort)
         array_out.append(name_sort)
      
   for name_src in array_src:
      array_out.append(name_src)
      
   return array_out

def _write_data(writer, data):
    "Writes datachars to writer."
    data = data.replace("&", "&amp;").replace("<", "&lt;")
    data = data.replace("\"", "&quot;").replace(">", "&gt;")
    data = data.replace("\r", "&#x0D;").replace("\n", "&#x0A;")
    writer.write(data)

def writeTEXTnode(node, writer, indent, newl):
   data = node.data.strip(" \r\n\t")
   if len(data) > 0:
      _write_data(writer, "%s%s%s"%(indent, data, newl))

def writeELEMENTnode(node, writer, indent, addindent, newl, platform):
   if platform == 'x360' and node.tagName == "Tool":
      indent = addindent+addindent+addindent

   writer.write(indent+"<"+node.tagName)
   
   attrs = node._get_attributes()
   a_names = attrs.keys()
   if len(a_names) > 0:
      a_names = sortForVCPrj(a_names)
      for a_name in a_names:
         writer.write("%s%s%s%s=\"" % (newl, addindent, indent, a_name))
         _write_data(writer, attrs[a_name].value)
         writer.write("\"")

   if node.childNodes:
      if len(a_names) > 0:
         writer.write(newl+indent+addindent)
      writer.write(">%s"%(newl))
      for each_node in node.childNodes:
         writexmlnode(each_node,writer,indent+addindent,addindent,newl,platform)
      writer.write("%s</%s>%s"%(indent,node.tagName,newl))
   else:
      writer.write("%s%s/>%s"%(newl,indent,newl))
      
def writexmlnode(node, writer, indent, addindent, newl, platform):
   if node.nodeType == Node.TEXT_NODE:
      writeTEXTnode(node, writer, indent, newl)
   elif node.nodeType == Node.ELEMENT_NODE:
      writeELEMENTnode(node, writer, indent, addindent, newl, platform)
   else:
      node.writexml(writer, indent, addindent, newl)
      
def saveDocument(name, node):
   platform = 'pc'
   if 'x360' in name.lower():
      platform = 'x360'
   elif 'ps3' in name.lower():
      platform = 'ps3'
   
   outputfile = open(name, "w")
   outputfile.write('<?xml version="1.0" ?>\n')
   
   for child_node in node.childNodes:
      writexmlnode(child_node, outputfile, "", "\t", "\n", platform)
